iT邦幫忙

2023 iThome 鐵人賽

DAY 13
0
自我挑戰組

TypeScript 從0開始系列 第 13

D13 - Todo list with React (2)

  • 分享至 

  • xImage
  •  
import React, { useState, useRef, useEffect } from "react";
import TodoList from "./TodoList";
import {v4 as uuidV4} from 'uuid'
// react manages states in app => state chages, then re-render
// hook: 
//     useState: return an array, specifically, [array, function]
//     useRef: reference elements inside HTML
//     useEffect: define a function to do things when argument passed into useEffect() changes


function App() {
  const LOCAL_STORAGE_KEY = "TODOS"

  // * Object destructuring
  const [todos, setTodos] = useState([])
  //                        ^^^^^^^^ argument is the initial state
  //            ^^^^^^^ function to update `todos`
  //     ^^^^^ array that return by useState()

  const todoTitleRef = useRef()

  useEffect(() => {
    console.log("loadItem()")
    console.log(localStorage.getItem(LOCAL_STORAGE_KEY))

    const localTodos = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY))
    if (localTodos) {
      setTodos((previousTodo) => {
        return [...previousTodo, ...localTodos]
      })
    }
  }, [])
  // ^^ pass an empty array, then it will run exactly once
  // since the empty array will not change

  useEffect(() => {
    console.log("setItem()")
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos))
  }, [todos])

  function handleAddTodo(e) {
    const title = todoTitleRef.current.value 

    if (title === "") return
    
    setTodos((previousTodo) => {
      return [...previousTodo, {id: uuidV4(), title: title, completed: false}]
    })

    todoTitleRef.current.value = ""
  } // handleAddTodo()

  function toggleTodo(id) {
    // make a copy of current todos
    const newTodos = [...todos]
    const toBeToggled = newTodos.find((todo) => todo.id === id)
    toBeToggled.completed = !toBeToggled.completed

    setTodos(newTodos)
  }


  return (
    <>
    
      <TodoList todos={todos} toggleTodo={toggleTodo} />
      {/* every components has `props` */}
      <input type="text" ref={todoTitleRef} />
      <input type="button" value="Add Todo" onClick={handleAddTodo}/>
      <input type="button" value="Clear Completed" />
      <p>0 left to do</p>
    </>
  );
}

export default App;


上一篇
D12 - Todo list with React
下一篇
D14 - 鐵人開賽兩週小心得
系列文
TypeScript 從0開始21
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言